package cn.com.basic.framework.datasource.config;

import cn.com.basic.framework.datasource.enums.DataSourceType;
import com.zaxxer.hikari.HikariDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@MapperScan
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties("spring.datasource.one")
    public DataSource master() {
        DataSource dataSource = new HikariDataSource();
        return dataSource;
    }

    @Bean
    @ConfigurationProperties("spring.datasource.two")
    public DataSource slave() {
        DataSource dataSource = new HikariDataSource();
        return dataSource;
    }

    @Primary
    @Bean
    @DependsOn({"master", "slave"})
    public DataSource dataSource(DataSource master, DataSource slave) {
        DynamicDataSourceContextHolder datasource
                = new DynamicDataSourceContextHolder();
        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put(DataSourceType.MASTER, master);
        targetDataSources.put(DataSourceType.SLAVE, slave);
        datasource.setTargetDataSources(targetDataSources);
        datasource.setDefaultTargetDataSource(master);
        return datasource;
    }
}
